//
//  RegisterViewController.m
//  QuickCure
//
//  Created by haoge on 16/9/10.
//  Copyright © 2016年 haoge. All rights reserved.
//

#import "RegisterViewController.h"
#import "HomeViewController.h"
#import "SVProgressHUD.h"

@interface RegisterViewController ()


@property (nonatomic,weak)UIButton *testBtn;

@property (nonatomic,assign) NSInteger secondsCountDown;

@property(nonatomic,strong)NSTimer *myTimer;


// ****************** 短信验证 ************************

@property(nonatomic,strong)UITextField *phoneTF;//电话号码
@property(nonatomic,strong)UITextField *verityTF;//验证码
@property(nonatomic,strong)UIButton *sendVerityBut;//发送验证码
@property(nonatomic,strong)UIButton *verityCodeBut;//验证码是否正确
@property(nonatomic,strong)NSTimer *timer;//用来倒计时的
@property(nonatomic,assign)int sumTime;//倒计时用的总时间
@property(nonatomic,strong)UIAlertController *alertC;//提示框

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   

    [self setupView];
    [self setUpVerifyPhoneNum];
    
}


- (void)setupView
{
    
    self.title = @"注册";
     self.phoneTF = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 335, 35)];
    //边框样式
    self.phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    //占位符
    self.phoneTF.placeholder = @"请输入您的手机号";
    
    //输入内容限制
    self.phoneTF.keyboardType = UIKeyboardTypePhonePad;
    
    [self.view addSubview:self.phoneTF];

     self.verityTF = [[UITextField alloc]initWithFrame:CGRectMake(20, 95, 190, 35)];
    //边框样式
    self.verityTF.borderStyle = UITextBorderStyleRoundedRect;
    //占位符
    self.verityTF.placeholder = @"请输入验证码";
    
    [self.view addSubview:self.verityTF];

    //验证码btn
    self.sendVerityBut = [[UIButton alloc]initWithFrame:CGRectMake(230, 95, 130, 35)];
    
    //倒计时
    _secondsCountDown = 60;
    //点击事件
    [self.sendVerityBut addTarget:self action:@selector(testbutton) forControlEvents:UIControlEventTouchUpInside];

    //占位符
    [self.sendVerityBut setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.sendVerityBut.titleLabel.font = [UIFont systemFontOfSize:14];
    
    
    [self.sendVerityBut setBackgroundColor:[UIColor grayColor]];
   
    [self.view addSubview:self.sendVerityBut];
    
    
    //圆点按钮
    UIButton *pointBtn = [[UIButton alloc]initWithFrame:CGRectMake(50, 152, 15, 15)];
    
    //点击事件
    [pointBtn addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    //默认没点
    [pointBtn setBackgroundImage:[UIImage imageNamed:@"illness_rb_img_nor.png"] forState:UIControlStateNormal];
    
    //选中有点
    [pointBtn setBackgroundImage:[UIImage imageNamed:@"illness_rb_img_sel.png"] forState:UIControlStateSelected];
    
    //添加
    [self.view addSubview:pointBtn];

    UILabel *userLabel = [[UILabel alloc]initWithFrame:CGRectMake(75, 140, 130, 40)];
    
    userLabel.text = @"本人同意并阅读";
    
    
    [self.view addSubview:userLabel];
    
    
    UIButton *userStatement = [[UIButton alloc]initWithFrame:CGRectMake(210, 140, 75, 40)];
    
    [userStatement setTitle:@"用户协议" forState:UIControlStateNormal];
    
    [userStatement setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    userStatement.titleLabel.font = [UIFont systemFontOfSize:14];
    
    [self.view addSubview:userStatement];
    
    
    self.verityCodeBut = [[UIButton alloc]initWithFrame:CGRectMake(20, 200, 335, 40)];
    
    [self.verityCodeBut  setTitle:@"注册" forState:UIControlStateNormal];
    
    [self.verityCodeBut  setBackgroundImage:[UIImage imageNamed:@"nav"] forState:UIControlStateNormal];
    
    [self.view addSubview:self.verityCodeBut];

}




- (void) selectBtn:(UIButton *)btn
{
    //如果是实心就禁用
    if (btn.isSelected) {
        
        btn.selected = NO;
    }
    //否则打开
    else
    {
        btn.selected = YES;
    }
}
- (void)testbutton
{
    _testBtn.enabled = NO;
    
    //每1秒执行一次
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) userInfo:nil repeats:YES];
    
}
- (void)time
{
     _secondsCountDown--;
    _testBtn.enabled = NO;

    
    [_testBtn setTitle:[NSString stringWithFormat:@"%ld 秒后重新获取",_secondsCountDown] forState:UIControlStateNormal];
    _testBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    if(_secondsCountDown<0){
       
        
        _testBtn.enabled = YES;
        [_testBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _secondsCountDown =60;
        
        [_myTimer invalidate];
        
        _myTimer = nil;
        
    }
  
}

//   *************************** 短信验证 ********************

- (void)setUpVerifyPhoneNum {
    
    self.sumTime = 60;
    [self.view addSubview:self.phoneTF];
    [self.view addSubview:self.verityTF];
    [self.view addSubview:self.sendVerityBut];
    [self.view addSubview:self.verityCodeBut];
    [self.sendVerityBut addTarget:self action:@selector(VerityAction) forControlEvents:UIControlEventTouchUpInside];
    [self.verityCodeBut addTarget:self action:@selector(verityCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - 发送按钮

- (void)VerityAction {
    //判断用户是否输入手机号码 手机号码是否正确
    if(self.phoneTF.text.length == 0) {
        [self alertActionWithTitle:@"提示" message:@"请输入手机号码"];
        return;
    }
    if (self.phoneTF.text.length != 11) {
        NSLog(@"电话号码输入有误");
        [self alertActionWithTitle:@"提示" message:@"电话号码输入有误"];
        return;
    }
    //每次将要发送验证码的时候需要将总时间变为60秒
    self.sumTime = 60;
    //关闭按钮的交互
    self.sendVerityBut.enabled = NO;
    //打开计时器
    [self.timer setFireDate:[NSDate distantPast]];
    //说明手机号码正确,可以进行发送验证码的操作
    [self sendVerityAction];
}
//发送验证码
- (void)sendVerityAction {
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneTF.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        if (error) {
            NSLog(@"请检查手机号码是否正确");
            [self alertActionWithTitle:@"提示" message:@"请检查手机号码是否正确"];
        } else {
            NSLog(@"验证码已发送");
            [self alertActionWithTitle:@"提示" message:@"验证码已发送"];
        }
    }];
}

#pragma mark - 检测按钮
//判断验证码是否正确
- (void)verityCodeAction:(UIButton*)sender {
    if (self.verityTF.text.length == 0) {
        NSLog(@"请输入验证码");
        [self alertActionWithTitle:@"提示" message:@"请输入验证码"];
        return;
    }
    //将验证码发送到服务器,判断验证码是否正确
    [self checkVerityCode];
}

- (void)checkVerityCode {
    
    [SMSSDK commitVerificationCode:self.verityTF.text phoneNumber:self.phoneTF.text zone:@"86" result:^(NSError *error) {
        if (error) {
            NSLog(@"验证码有误");
            //说明60秒已经结束并且还没有得到验证码,这时候我们应该将定时器暂停或者销毁
            [self alertActionWithTitle:@"验证码错误" message:@"你输入的验证码有误,请重新输入!"];
            [self.sendVerityBut setTitle:@"再次发送" forState:UIControlStateNormal];
            //打开用户交互
            self.sendVerityBut.enabled = YES;
            //销毁定时器
            [self.timer invalidate];
            self.timer = nil;
        } else {
            // =============================
            NSLog(@"验证成功");
            [SVProgressHUD setMinimumDismissTimeInterval:1];
            [SVProgressHUD showSuccessWithStatus:@"注册成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

#pragma mark - 懒加载

- (UITextField*)phoneTF {
    if (!_phoneTF) {
        _phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 200, 200, 40)];
        _phoneTF.borderStyle = UITextBorderStyleRoundedRect;
        _phoneTF.placeholder = @"请输入手机号码";
        //需要设置数字键盘
        _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _phoneTF;
}
- (UITextField *)verityTF {
    if (!_verityTF) {
        _verityTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 280, 200, 40)];
        _verityTF.borderStyle = UITextBorderStyleRoundedRect;
        _verityTF.placeholder = @"请输入验证码";
    }
    return _verityTF;
}

- (UIButton*)sendVerityBut {
    if (!_sendVerityBut) {
        _sendVerityBut = [[UIButton alloc] initWithFrame:CGRectMake(260, 200, 80, 40)];
        _sendVerityBut.backgroundColor = [UIColor lightGrayColor];
        _sendVerityBut.layer.cornerRadius = 10;
        [_sendVerityBut setTitle:@"发送" forState:UIControlStateNormal];
    }
    return _sendVerityBut;
}



- (NSTimer*)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        //暂停
        [_timer setFireDate:[NSDate distantFuture]];
    }
    return _timer;
}
//计时器回调方法
- (void)timerAction {
    
    //把按钮的标题变为倒计时
    self.sumTime--;//每次执行倒计时方法,让总时间-1
    //    NSString *butTitle = @"";//按钮标题
    
    if (self.sumTime >= 0) {
        
        [self.sendVerityBut setTitle:[NSString stringWithFormat:@"%ds",self.sumTime] forState:UIControlStateNormal];
    } else {
        //说明60秒已经结束并且还没有得到验证码,这时候我们应该将定时器暂停或者销毁
        [self.sendVerityBut setTitle:@"再次发送" forState:UIControlStateNormal];
        //打开用户交互
        self.sendVerityBut.enabled = YES;
        //销毁定时器
        [self.timer invalidate];
        self.timer = nil;
    }
    
}

#pragma mark - 当视图消失
- (void)viewDidDisappear:(BOOL)animated {
    self.sumTime = 60;
    [self.timer invalidate];
    self.timer = nil;
    [self.sendVerityBut setTitle:@"发送" forState:UIControlStateNormal];
    self.phoneTF.text = nil;
    self.verityTF.text = nil;
    [super viewDidDisappear:YES];
}

#pragma mark - 提示框
- (void)alertActionWithTitle:(NSString*)title message:(NSString*)message {
    
    
    self.alertC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //create the actions
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    //Add the actions
    [self.alertC addAction:cancelAction];
    [self.alertC addAction:okAction];
    [self presentViewController:self.alertC animated:YES completion:nil];
}

@end

























